<template>
  <div class="dashboard-container">
    <div class="dashboard-content">
      <div class="sidebar">
        <div class="section-title">
          <el-icon>
            <Calendar />
          </el-icon>
          <span>快速导航</span>
        </div>
        <el-menu :default-active="activeModule" class="dashboard-menu" @select="handleMenuSelect">
          <el-menu-item index="consultations">
            <el-icon>
              <Calendar />
            </el-icon>
            <span>预约管理</span>
          </el-menu-item>
          <template v-if="userStore.user?.role === 'admin'">
            <el-menu-item index="courses">
              <el-icon>
                <Reading />
              </el-icon>
              <span>课程管理</span>
            </el-menu-item>
            <el-menu-item index="events">
              <el-icon>
                <Location />
              </el-icon>
              <span>活动管理</span>
            </el-menu-item>
            <el-menu-item index="knowledge">
              <el-icon>
                <Document />
              </el-icon>
              <span>养老知识</span>
            </el-menu-item>
            <el-menu-item index="users">
              <el-icon>
                <User />
              </el-icon>
              <span>用户管理</span>
            </el-menu-item>
          </template>
        </el-menu>
      </div>
      <div class="main-content">
        <!-- 系统概览 -->
        <div class="overview-section">
          <div class="gradient-banner">
            <div class="banner-content">
              <div class="user-info">
                <div class="avatar-wrapper">
                  <el-avatar :size="80" :src="userStore.user?.avatar_url
                      ? `http://localhost:3000${userStore.user.avatar_url}`
                      : '/images/default-avatar.png'
                    " @error="() => true">
                    <img src="/images/default-avatar.png" alt="默认头像" />
                  </el-avatar>
                </div>
                <div class="user-details">
                  <div class="user-title">
                    <h2>{{ userStore.user?.username }}</h2>
                    <div class="user-tags">
                      <el-tag v-if="userStore.user?.role === 'admin'" size="small" effect="dark" class="admin-tag">
                        管理员
                      </el-tag>
                      <el-tag v-else-if="userStore.user?.role === 'nurse'" size="small" effect="dark" class="admin-tag">
                        服务人员
                      </el-tag>
                    </div>
                  </div>
                  <div class="user-id">ID: {{ userStore.user?.id || '-' }}</div>
                </div>
              </div>
              <div class="platform-info">
                <p class="slogan">用科技提升养老服务质量，让晚年生活更有尊严</p>
              </div>
            </div>
          </div>
          <div class="stats-cards">
            <el-card class="stat-card">
              <template #header>
                <div class="card-header">
                  <el-icon>
                    <Calendar />
                  </el-icon>
                  <span>待处理预约</span>
                </div>
              </template>
              <div class="stat-value">{{ pendingConsultations.length }}</div>
            </el-card>
            <template v-if="userStore.user?.role === 'admin'">
              <el-card class="stat-card">
                <template #header>
                  <div class="card-header">
                    <el-icon>
                      <Reading />
                    </el-icon>
                    <span>进行中课程</span>
                  </div>
                </template>
                <div class="stat-value">{{ courses.length }}</div>
              </el-card>
              <el-card class="stat-card">
                <template #header>
                  <div class="card-header">
                    <el-icon>
                      <Location />
                    </el-icon>
                    <span>全部活动</span>
                  </div>
                </template>
                <div class="stat-value">{{ events.length }}</div>
              </el-card>
              <el-card class="stat-card">
                <template #header>
                  <div class="card-header">
                    <el-icon>
                      <Document />
                    </el-icon>
                    <span>知识库</span>
                  </div>
                </template>
                <div class="stat-value">{{ knowledgeList.length }}</div>
              </el-card>
            </template>
          </div>
        </div>

        <div class="section-header">
          <div class="section-title">
            <el-icon>
              <component :is="getModuleIcon" />
            </el-icon>
            <span>{{ getModuleTitle() }}</span>
          </div>
          <el-button v-if="shouldShowAddButton" type="primary" @click="handleAdd">
            <el-icon>
              <Plus />
            </el-icon>新增{{ getModuleTitle() }}
          </el-button>
        </div>

        <!-- 数据表格区域 -->
        <div class="data-table">
          <div v-if="getActiveData.length === 0" class="empty-state">
            <div class="empty-icon">
              <el-icon>
                <component :is="getModuleIcon" />
              </el-icon>
            </div>
            <div class="empty-text">暂无{{ getModuleTitle() }}记录</div>
          </div>
          <el-table v-else :data="getActiveData" style="width: 100%" :row-class-name="tableRowClassName"
            @row-click="handleRowClick">
            <!-- 预约管理列 -->
            <template v-if="activeModule === 'consultations'">
              <el-table-column prop="username" label="预约用户" min-width="120">
                <template #default="{ row }">
                  <el-tag size="small" effect="plain">{{ row.username }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="service_type" label="服务类型" min-width="120">
                <template #default="{ row }">
                  <el-tag :type="row.service_type === 'home' ? 'success' : 'primary'" effect="plain" size="small">
                    {{ row.service_type === 'home' ? '上门护理' : '陪诊服务' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="date" label="预约日期" min-width="180">
                <template #default="{ row }">
                  <div class="date-column">
                    <el-icon>
                      <Calendar />
                    </el-icon>
                    <span>{{ formatDateTime(row.date, row.time) }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="status" label="状态" min-width="100" align="center">
                <template #default="{ row }">
                  <el-tag size="small" :type="getStatusType(row.status)">
                    {{ getStatusText(row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" min-width="120" align="center">
                <template #default="{ row }">
                  <div class="operation-column">
                    <template v-if="row.status === 'pending'">
                      <el-button-group>
                        <el-button size="small" type="primary"
                          @click.stop="updateConsultationStatus(row.id, 'confirmed')">接受</el-button>
                        <el-button size="small" type="success"
                          @click.stop="updateConsultationStatus(row.id, 'completed')">完成</el-button>
                      </el-button-group>
                    </template>
                    <template v-else-if="row.status === 'confirmed'">
                      <el-button size="small" type="success"
                        @click.stop="updateConsultationStatus(row.id, 'completed')">完成服务</el-button>
                    </template>
                    <template v-else>
                      <el-tag size="small" type="success">已完成</el-tag>
                    </template>
                  </div>
                </template>
              </el-table-column>
            </template>

            <!-- 用户管理列 -->
            <template v-else-if="activeModule === 'users'">
              <el-table-column prop="username" label="用户名" min-width="120">
                <template #default="{ row }">
                  <el-tag size="small" effect="plain">{{ row.username }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="role" label="角色" min-width="120">
                <template #default="{ row }">
                  <el-tag :type="row.role === 'admin' ? 'danger' : row.role === 'nurse' ? 'warning' : 'info'
                    " effect="plain" size="small">
                    {{
                      row.role === 'admin'
                        ? '管理员'
                        : row.role === 'nurse'
                          ? '服务人员'
                          : '普通用户'
                    }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" min-width="120" align="center">
                <template #default="{ row }">
                  <div class="operation-column">
                    <el-button-group>
                      <el-button size="small" type="danger" @click="handleDeleteUser(row.id)" :disabled="!row.id">
                        <el-icon>
                          <Delete />
                        </el-icon>
                      </el-button>
                    </el-button-group>
                  </div>
                </template>
              </el-table-column>
            </template>
            <!-- 其他模块通用列 -->
            <template v-else>
              <el-table-column prop="title" label="标题" min-width="180">
                <template #default="{ row }">
                  <div class="title-column">
                    <el-icon>
                      <component :is="getModuleIcon" />
                    </el-icon>
                    <span class="title-text">{{
                      activeModule === 'events' ? row.name : row.title
                      }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column prop="description" label="描述" min-width="280">
                <template #default="{ row }">
                  <div class="description-column">
                    <div class="description-text">
                      {{
                        (activeModule === 'knowledge' ? row.content : row.description).length > 50
                          ? (activeModule === 'knowledge' ? row.content : row.description).slice(
                            0,
                            50,
                          ) + '...'
                          : activeModule === 'knowledge'
                            ? row.content
                            : row.description
                      }}
                    </div>
                    <div v-if="activeModule === 'events'" class="event-date">
                      <el-icon>
                        <Calendar />
                      </el-icon>
                      <span>{{ formatDate(row.date) }}</span>
                    </div>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="100" align="center">
                <template #default="{ row }">
                  <div class="operation-column">
                    <el-button-group>
                      <el-button v-if="activeModule !== 'events'" circle size="small" type="primary"
                        @click="handleEdit(row)">
                        <el-icon>
                          <Edit />
                        </el-icon>
                      </el-button>
                      <el-button circle size="small" type="danger" @click="handleDelete(row)">
                        <el-icon>
                          <Delete />
                        </el-icon>
                      </el-button>
                    </el-button-group>
                  </div>
                </template>
              </el-table-column>
            </template>
          </el-table>
        </div>
      </div>
    </div>

    <!-- 编辑/新增弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogType === 'add' ? '新增' + getModuleTitle() : '编辑' + getModuleTitle()"
      width="500px">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" style="max-width: 460px">
        <template v-if="activeModule === 'courses'">
          <el-form-item label="课程名称" prop="title">
            <el-input v-model="formData.title" placeholder="请输入课程名称" />
          </el-form-item>
          <el-form-item label="授课老师" prop="teacher">
            <el-input v-model="formData.teacher" placeholder="请输入授课老师" />
          </el-form-item>
          <el-form-item label="课程安排" prop="schedule">
            <el-input v-model="formData.schedule" placeholder="请输入课程安排" />
          </el-form-item>
          <el-form-item label="课程描述" prop="description">
            <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请输入课程描述" />
          </el-form-item>
          <el-form-item label="视频路径" prop="video_path">
            <el-input v-model="formData.video_path" placeholder="请输入视频名称，例如：课程1.mp4">
              <template #prefix>
                <el-icon>
                  <VideoCamera />
                </el-icon>
              </template>
            </el-input>
            <el-alert title="视频存放说明" type="info" description="请将课程视频放在backend/public/uploads/courses/videos下，并粘贴视频名称"
              show-icon :closable="false" style="margin-top: 8px" />
          </el-form-item>
        </template>

        <template v-if="activeModule === 'events'">
          <el-form-item label="活动名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入活动名称" />
          </el-form-item>
          <el-form-item label="活动地点" prop="location">
            <el-input v-model="formData.location" placeholder="请输入活动地点" />
          </el-form-item>
          <el-form-item label="活动日期" prop="date">
            <el-date-picker v-model="formData.date" type="date" placeholder="请选择活动日期" style="width: 100%" />
          </el-form-item>
          <el-form-item label="活动描述" prop="description">
            <el-input v-model="formData.description" type="textarea" rows="3" placeholder="请输入活动描述" />
          </el-form-item>
          <el-form-item label="图片路径" prop="image_path">
            <el-input v-model="formData.image_path" placeholder="请输入图片名称，例如：活动1.jpg">
              <template #prefix>
                <el-icon>
                  <Picture />
                </el-icon>
              </template>
            </el-input>
            <el-alert title="图片存放说明" type="info" description="请将活动图片放在backend/public/uploads/events下，并粘贴图片名称" show-icon
              :closable="false" style="margin-top: 8px" />
          </el-form-item>
        </template>

        <template v-if="activeModule === 'knowledge'">
          <el-form-item label="文章标题" prop="title">
            <el-input v-model="formData.title" placeholder="请输入文章标题" />
          </el-form-item>
          <el-form-item label="文章内容" prop="content">
            <el-input v-model="formData.content" type="textarea" rows="4" placeholder="请输入文章内容" />
          </el-form-item>
        </template>

        <template v-if="activeModule === 'consultations'">
          <el-form-item label="服务类型" prop="service_type">
            <el-select v-model="formData.service_type" placeholder="请选择服务类型" style="width: 100%">
              <el-option label="上门护理" value="home" />
              <el-option label="陪诊服务" value="escort" />
            </el-select>
          </el-form-item>
          <el-form-item label="预约用户" prop="username">
            <el-select v-model="formData.username" placeholder="请选择用户" style="width: 100%">
              <el-option v-for="user in userList" :key="user.id" :label="user.username" :value="user.username" />
            </el-select>
          </el-form-item>
          <el-form-item label="预约日期" prop="date">
            <el-date-picker v-model="formData.date" type="date" placeholder="请选择预约日期" style="width: 100%" />
          </el-form-item>
          <el-form-item label="预约时间" prop="time">
            <el-time-select v-model="formData.time" start="08:00" step="00:30" end="18:00" placeholder="请选择预约时间"
              style="width: 100%" />
          </el-form-item>
        </template>

        <template v-if="activeModule === 'users'">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="formData.username" placeholder="请输入用户名" />
          </el-form-item>
          <el-form-item label="角色" prop="role">
            <el-select v-model="formData.role" placeholder="请选择角色" style="width: 100%">
              <el-option label="管理员" value="admin" />
              <el-option label="服务人员" value="nurse" />
              <el-option label="普通用户" value="user" />
            </el-select>
          </el-form-item>
          <el-form-item label="会员状态" prop="isVip">
            <el-switch v-model="formData.isVip" active-text="VIP会员" inactive-text="普通会员" />
          </el-form-item>
          <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
            <el-input v-model="formData.password" type="password" placeholder="请输入密码" />
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 预约详情模态框 -->
    <el-dialog v-model="detailDialogVisible" title="预约详情" width="600px">
      <div class="consultation-detail">
        <div class="detail-section">
          <div class="section-title">基本信息</div>
          <div class="detail-item">
            <span class="label">预约用户：</span>
            <span class="value">{{ selectedConsultation?.username }}</span>
          </div>
          <div class="detail-item">
            <span class="label">患者姓名：</span>
            <span class="value">{{ selectedConsultation?.patient_name }}</span>
          </div>
          <div class="detail-item">
            <span class="label">联系电话：</span>
            <span class="value">{{ selectedConsultation?.phone }}</span>
          </div>
          <div class="detail-item">
            <span class="label">预约时间：</span>
            <span class="value">{{
              formatDateTime(selectedConsultation?.date, selectedConsultation?.time)
              }}</span>
          </div>
          <div class="detail-item">
            <span class="label">服务地址：</span>
            <span class="value">{{ selectedConsultation?.address }}</span>
          </div>
        </div>

        <div class="detail-section">
          <div class="section-title">服务信息</div>
          <div class="detail-item">
            <span class="label">服务类型：</span>
            <el-tag size="small" :type="getServiceTagType(selectedConsultation?.service_type)">
              {{ getServiceTypeText(selectedConsultation?.service_type) }}
            </el-tag>
          </div>
          <div class="detail-item">
            <span class="label">服务费用：</span>
            <span class="value price">¥ {{ selectedConsultation?.total_price || '0.00' }}</span>
          </div>
          <div class="detail-item">
            <span class="label">服务项目：</span>
            <div class="service-list">
              <el-tag v-for="service in selectedConsultation?.services" :key="service.id" size="small"
                class="service-tag">
                {{ service.service_name }} - ¥{{ service.service_price }}
              </el-tag>
            </div>
          </div>
        </div>

        <div class="detail-section">
          <div class="section-title">订单状态</div>
          <div class="detail-item">
            <span class="label">当前状态：</span>
            <el-tag size="small" :type="getStatusType(selectedConsultation?.status)">
              {{ getStatusText(selectedConsultation?.status) }}
            </el-tag>
          </div>
          <div class="detail-item">
            <span class="label">创建时间：</span>
            <span class="value">{{ formatDateTime(selectedConsultation?.created_at) }}</span>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, watch } from 'vue'
import { VideoCamera } from '@element-plus/icons-vue'
import { Picture } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import {
  Location,
  Calendar,
  User,
  Plus,
  Reading,
  Document,
  Edit,
  Delete,
  Setting,
} from '@element-plus/icons-vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import api from '@/api'
import { useRouter } from 'vue-router'

const userStore = useUserStore()
const router = useRouter()

// 问诊/任务列表
const consultations = ref([])
// 活动列表
const events = ref([])
// 课程列表
const courses = ref([])
// 养老知识列表
const knowledgeList = ref([])
// 用户列表
const userList = ref([])

const props = defineProps({
  activeModule: {
    type: String,
    default: 'consultations',
  },
})

const emit = defineEmits(['switch-module'])

// 获取预约列表
const fetchConsultations = async () => {
  try {
    const response = await api.get('/consultations')
    console.log('获取到的预约列表数据:', response.data)
    console.log(
      '预约数据中的用户名:',
      response.data.map((item) => item.username),
    )
    consultations.value = response.data
    return response.data
  } catch (error) {
    console.error('获取预约列表失败:', error)
    ElMessage.error('获取预约列表失败')
    throw error
  }
}

const fetchEvents = async () => {
  try {
    console.log('开始获取活动列表')
    const response = await api.get('/events')
    console.log('获取到的活动列表数据:', response.data)
    events.value = response.data
    return response.data
  } catch (error) {
    console.error('获取活动列表失败:', error)
    console.error('错误详情:', {
      message: error.message,
      response: error.response?.data,
      status: error.response?.status,
    })
    ElMessage.error('获取活动列表失败')
    throw error
  }
}

const fetchCourses = async () => {
  try {
    console.log('开始获取课程列表')
    const response = await api.get('/courses')
    console.log('获取到的课程列表数据:', response.data)
    courses.value = response.data
    return response.data
  } catch (error) {
    console.error('获取课程列表失败:', error)
    console.error('错误详情:', {
      message: error.message,
      response: error.response?.data,
      status: error.response?.status,
    })
    ElMessage.error('获取课程列表失败')
    throw error
  }
}

const fetchKnowledge = async () => {
  try {
    console.log('开始获取知识列表')
    const response = await api.get('/knowledge')
    console.log('获取到的知识列表数据:', response.data)
    knowledgeList.value = response.data
    return response.data
  } catch (error) {
    console.error('获取知识列表失败:', error)
    console.error('错误详情:', {
      message: error.message,
      response: error.response?.data,
      status: error.response?.status,
    })
    ElMessage.error('获取知识列表失败')
    throw error
  }
}

// 获取用户列表
const fetchUsers = async () => {
  try {
    const response = await api.get('/users')
    console.log('获取到的用户列表数据:', response.data)
    userList.value = response.data
  } catch (error) {
    console.error('获取用户列表失败:', error)
    ElMessage.error('获取用户列表失败')
  }
}

// 当前选中的模块
const activeModule = computed(() => props.activeModule)

// 监听 activeModule 变化
watch(
  activeModule,
  (newModule) => {
    console.log('Active module changed:', newModule)
    // 根据模块类型加载对应数据
    switch (newModule) {
      case 'consultations':
        fetchConsultations()
        break
      case 'courses':
        fetchCourses()
        break
      case 'events':
        fetchEvents()
        break
      case 'knowledge':
        fetchKnowledge()
        break
      case 'users':
        fetchUsers()
        break
    }
  },
  { immediate: true },
)

// 初始化数据
const initData = async () => {
  try {
    console.log('初始化数据，用户角色:', userStore.user?.role)
    if (!userStore.user) {
      console.error('用户未登录或用户信息未加载')
      return
    }

    // 分别处理每个模块的数据加载
    try {
      console.log('开始加载预约数据...')
      await fetchConsultations()
      console.log('预约数据加载成功')
    } catch (error) {
      console.error('加载预约数据失败:', error.message)
      ElMessage.error('预约数据加载失败')
    }

    try {
      console.log('开始加载活动数据...')
      await fetchEvents()
      console.log('活动数据加载成功')
    } catch (error) {
      console.error('加载活动数据失败:', error.message)
      ElMessage.error('活动数据加载失败')
    }

    try {
      console.log('开始加载课程数据...')
      await fetchCourses()
      console.log('课程数据加载成功')
    } catch (error) {
      console.error('加载课程数据失败:', error.message)
      ElMessage.error('课程数据加载失败')
    }

    try {
      console.log('开始加载知识库数据...')
      await fetchKnowledge()
      console.log('知识库数据加载成功')
    } catch (error) {
      console.error('加载知识库数据失败:', error.message)
      ElMessage.error('知识库数据加载失败')
    }

    try {
      console.log('开始加载用户数据...')
      await fetchUsers()
      console.log('用户数据加载成功')
    } catch (error) {
      console.error('加载用户数据失败:', error.message)
      ElMessage.error('用户数据加载失败')
    }
    console.log('所有数据加载完成，当前模块:', activeModule.value)
  } catch (error) {
    console.error('初始化数据失败:', {
      error: error.message,
      response: error.response?.data,
      status: error.response?.status,
    })
    ElMessage.error('加载数据失败，请刷新页面重试')
  }
}

// 监听路由变化
watch(
  () => router.currentRoute.value.path,
  (newPath) => {
    console.log('路由变化:', newPath)
    if (newPath === '/staff') {
      console.log('当前在管理页面')
      initData()
    }
  },
  { immediate: true },
)

// 格式化日期
const formatDate = (date) => {
  const d = new Date(date)
  const year = d.getFullYear()
  const month = (d.getMonth() + 1).toString().padStart(2, '0')
  const day = d.getDate().toString().padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 'pending':
      return 'warning'
    case 'confirmed':
      return 'primary'
    case 'completed':
      return 'success'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 'pending':
      return '待处理'
    case 'confirmed':
      return '已确认'
    case 'completed':
      return '已完成'
    default:
      return '未知'
  }
}

// 已完成的任务
const completedTasks = computed(() => {
  return consultations.value.filter((task) => task.status === 'completed')
})

// 格式化日期时间
const formatDateTime = (date, time) => {
  return `${formatDate(date)} ${time || ''}`
}

// 更新预约状态
const updateConsultationStatus = async (id, status) => {
  try {
    await api.put(`/consultations/${id}/status`, { status })
    await fetchConsultations()
    ElMessage.success('状态更新成功')
  } catch (error) {
    console.error('更新状态失败:', error)
    ElMessage.error('更新状态失败')
  }
}

// 删除活动
const handleDeleteEvent = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个活动吗？', '提示', {
      type: 'warning',
    })
    await api.delete(`/events/${id}`)
    ElMessage.success('删除成功')
    await fetchEvents()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除活动失败:', error)
      ElMessage.error('删除活动失败')
    }
  }
}

// 删除课程
const handleDeleteCourse = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个课程吗？', '提示', {
      type: 'warning',
    })
    await api.delete(`/courses/${id}`)
    ElMessage.success('删除成功')
    await fetchCourses()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除课程失败:', error)
      ElMessage.error('删除课程失败')
    }
  }
}

// 删除知识文章
const handleDeleteKnowledge = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这篇文章吗？', '提示', {
      type: 'warning',
    })
    await api.delete(`/knowledge/${id}`)
    ElMessage.success('删除成功')
    await fetchKnowledge()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除文章失败:', error)
      ElMessage.error('删除文章失败')
    }
  }
} // 删除用户
const handleDeleteUser = async (id) => {
  try {
    // 先弹出确认框
    await ElMessageBox.confirm('确定要删除这个用户吗？此操作不可恢复', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    // 用户确认后继续删除操作
    const userId = parseInt(id, 10)
    if (isNaN(userId)) {
      throw new Error('无效的用户ID')
    }

    await api.delete(`/users/${userId}`)
    ElMessage.success('删除成功')
    await fetchUsers()
  } catch (error) {
    if (error === 'cancel') {
      // 用户点击取消按钮
      ElMessage({
        type: 'info',
        message: '已取消删除',
      })
    } else {
      // 实际的错误
      console.error('删除用户失败:', error)
      ElMessage.error('删除用户失败')
    }
  }
}

// 排序后的预约列表
const sortedConsultations = computed(() => {
  return [...consultations.value].sort((a, b) => {
    // 首先按状态排序：pending > confirmed > completed
    const statusOrder = { pending: 0, confirmed: 1, completed: 2 }
    const statusDiff = statusOrder[a.status] - statusOrder[b.status]
    if (statusDiff !== 0) return statusDiff

    // 然后按日期时间排序
    const dateA = new Date(`${a.date} ${a.time}`)
    const dateB = new Date(`${b.date} ${b.time}`)
    return dateA - dateB
  })
})

// 表格行样式
const tableRowClassName = ({ row }) => {
  if (row.status === 'pending') return 'warning-row'
  if (row.status === 'completed') return 'success-row'
  return ''
}

const getModuleTitle = () => {
  switch (props.activeModule) {
    case 'consultations':
      return '预约管理'
    case 'courses':
      return '课程管理'
    case 'events':
      return '活动管理'
    case 'knowledge':
      return '养老知识'
    default:
      return '预约管理'
  }
}

// 获取模块图标
const getModuleIcon = computed(() => {
  switch (activeModule.value) {
    case 'consultations':
      return Calendar
    case 'courses':
      return Reading
    case 'events':
      return Location
    case 'knowledge':
      return Document
    case 'users':
      return User
    default:
      return Calendar
  }
})

// 处理菜单选择
const handleMenuSelect = (index) => {
  console.log('Menu selected:', index)
  emit('switch-module', index)
}

// 获取当前模块的数据
const getActiveData = computed(() => {
  switch (activeModule.value) {
    case 'consultations':
      return sortedConsultations.value
    case 'courses':
      return courses.value
    case 'events':
      return events.value
    case 'knowledge':
      return knowledgeList.value
    case 'users':
      return userList.value
    default:
      return []
  }
})

// 统一的查看处理方法
const handleView = (row) => {
  switch (activeModule.value) {
    case 'courses':
      router.push(`/course/${row.id}`)
      break
    case 'events':
      router.push(`/event/${row.id}`)
      break
    case 'knowledge':
      router.push(`/knowledge/${row.id}`)
      break
  }
}

// 统一的删除处理方法
const handleDelete = async (row) => {
  try {
    const moduleTitle = getModuleTitle()
    console.log('准备删除数据:', {
      module: activeModule.value,
      id: row.id,
      url: `/${activeModule.value}/${row.id}`,
    })

    await ElMessageBox.confirm(
      `确定要删除这${moduleTitle === '养老知识' ? '篇文章' : '个' + moduleTitle.slice(0, 2)}吗？`,
      '提示',
      {
        type: 'warning',
      },
    )

    switch (activeModule.value) {
      case 'courses':
        try {
          console.log('发送删除课程请求:', { id: row.id })
          const response = await api.delete(`/courses/${row.id}`)
          console.log('课程删除响应:', response)
          await fetchCourses()
        } catch (error) {
          console.error('课程删除失败:', {
            error,
            id: row.id,
            response: error.response?.data,
            status: error.response?.status,
          })
          throw error
        }
        break
      case 'events':
        try {
          console.log('发送删除活动请求:', { id: row.id })
          const response = await api.delete(`/events/${row.id}`)
          console.log('活动删除响应:', response)
          await fetchEvents()
        } catch (error) {
          console.error('活动删除失败:', {
            error,
            id: row.id,
            response: error.response?.data,
            status: error.response?.status,
          })
          throw error
        }
        break
      case 'knowledge':
        try {
          console.log('发送删除知识请求:', { id: row.id })
          const response = await api.delete(`/knowledge/${row.id}`)
          console.log('知识删除响应:', response)
          await fetchKnowledge()
        } catch (error) {
          console.error('知识删除失败:', {
            error,
            id: row.id,
            response: error.response?.data,
            status: error.response?.status,
          })
          throw error
        }
        break
      case 'users':
        try {
          console.log('发送删除用户请求:', { id: row.id })
          const response = await api.delete(`/users/${row.id}`)
          console.log('用户删除响应:', response)
          await fetchUsers()
        } catch (error) {
          console.error('用户删除失败:', {
            error,
            id: row.id,
            response: error.response?.data,
            status: error.response?.status,
          })
          throw error
        }
        break
    }

    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除操作失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 获取模块标签类型
const getModuleTagType = (module) => {
  switch (module) {
    case 'courses':
      return 'success'
    case 'events':
      return 'warning'
    case 'knowledge':
      return 'info'
    default:
      return 'primary'
  }
}

// 弹窗相关
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const formRef = ref(null)
const formData = ref({})

// 表单校验规则
const formRules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
  teacher: [{ required: true, message: '请输入教师姓名', trigger: 'blur' }],
  schedule: [{ required: true, message: '请输入课程安排', trigger: 'blur' }],
  description: [{ required: true, message: '请输入描述', trigger: 'blur' }],
  location: [{ required: true, message: '请输入地点', trigger: 'blur' }],
  date: [{ required: true, message: '请选择日期', trigger: 'change' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
  service_type: [{ required: true, message: '请选择服务类型', trigger: 'change' }],
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  time: [{ required: true, message: '请选择预约时间', trigger: 'change' }],
  video_path: [{ required: true, message: '请填写视频路径', trigger: 'change' }],
}

// 处理新增
const handleAdd = () => {
  dialogType.value = 'add'
  formData.value = {}
  dialogVisible.value = true
}

// 处理编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  formData.value = { ...row }
  dialogVisible.value = true
}

// 处理表单提交
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    const submitData = { ...formData.value }

    if (activeModule.value === 'consultations') {
      // 格式化日期和时间
      const dateObj = new Date(submitData.date)
      submitData.date = formatDate(dateObj)
    }

    // 打印完整的提交数据
    console.log('提交数据详情:', {
      type: dialogType.value,
      module: activeModule.value,
      data: submitData,
    })

    if (dialogType.value === 'add') {
      switch (activeModule.value) {
        case 'consultations':
          try {
            console.log('发送新增预约请求:', submitData)
            const response = await api.post('/consultations', submitData)
            console.log('预约新增响应:', response.data)
            await fetchConsultations()
            ElMessage.success('预约创建成功')
            dialogVisible.value = false
          } catch (error) {
            console.error('预约新增失败:', {
              error,
              request: submitData,
              response: error.response?.data,
              status: error.response?.status,
            })
            ElMessage.error(error.response?.data?.message || '预约创建失败')
            throw error
          }
          break
        case 'courses':
          try {
            console.log('发送新增课程请求:', submitData)
            const response = await api.post('/courses', submitData)
            console.log('课程新增响应:', response)
            await fetchCourses()
          } catch (error) {
            console.error('课程新增失败:', {
              error,
              request: submitData,
              response: error.response?.data,
              status: error.response?.status,
            })
            throw error
          }
          break
        case 'events':
          try {
            console.log('发送新增活动请求:', submitData)
            const response = await api.post('/events', submitData)
            console.log('活动新增响应:', response)
            await fetchEvents()
          } catch (error) {
            console.error('活动新增失败:', {
              error,
              request: submitData,
              response: error.response?.data,
              status: error.response?.status,
            })
            throw error
          }
          break
        case 'knowledge':
          try {
            console.log('发送新增知识请求:', submitData)
            const response = await api.post('/knowledge', submitData)
            console.log('知识新增响应:', response)
            await fetchKnowledge()
          } catch (error) {
            console.error('知识新增失败:', {
              error,
              request: submitData,
              response: error.response?.data,
              status: error.response?.status,
            })
            throw error
          }
          break
      }
      ElMessage.success('新增成功')
    } else {
      const id = submitData.id
      switch (activeModule.value) {
        case 'courses':
          try {
            console.log('发送更新课程请求:', { id, data: submitData })
            const response = await api.put(`/courses/${id}`, submitData)
            console.log('课程更新响应:', response)
            await fetchCourses()
          } catch (error) {
            console.error('课程更新失败:', {
              error,
              id,
              request: submitData,
              response: error.response?.data,
              status: error.response?.status,
            })
            throw error
          }
          break
        case 'events':
          try {
            console.log('发送更新活动请求:', { id, data: submitData })
            const response = await api.put(`/events/${id}`, submitData)
            console.log('活动更新响应:', response)
            await fetchEvents()
          } catch (error) {
            console.error('活动更新失败:', {
              error,
              id,
              request: submitData,
              response: error.response?.data,
              status: error.response?.status,
            })
            throw error
          }
          break
        case 'knowledge':
          try {
            console.log('发送更新知识请求:', { id, data: submitData })
            const response = await api.put(`/knowledge/${id}`, submitData)
            console.log('知识更新响应:', response)
            await fetchKnowledge()
          } catch (error) {
            console.error('知识更新失败:', {
              error,
              id,
              request: submitData,
              response: error.response?.data,
              status: error.response?.status,
            })
            throw error
          }
          break
      }
      ElMessage.success('更新成功')
    }

    dialogVisible.value = false
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败，请重试')
  }
}

const pendingConsultations = computed(() => {
  return consultations.value.filter((c) => c.status !== 'completed')
})

// 添加预约详情相关的响应式变量
const detailDialogVisible = ref(false)
const selectedConsultation = ref(null)

// 添加表格行点击事件处理函数
const handleRowClick = (row) => {
  if (activeModule.value === 'consultations') {
    selectedConsultation.value = row
    detailDialogVisible.value = true
  }
}

// 获取服务类型标签样式
const getServiceTagType = (type) => {
  switch (type) {
    case 'basic':
      return 'info'
    case 'premium':
      return 'warning'
    case 'vip':
      return 'success'
    default:
      return 'info'
  }
}

// 获取服务类型文本
const getServiceTypeText = (type) => {
  switch (type) {
    case 'basic':
      return '基础护理'
    case 'premium':
      return '高级护理'
    case 'vip':
      return 'VIP护理'
    default:
      return '定制服务'
  }
}
// 添加是否显示新增按钮的计算属性
const shouldShowAddButton = computed(() => {
  if (activeModule.value === 'users') {
    return false
  }
  if (activeModule.value === 'consultations') {
    return userStore.user?.role === 'user'
  }
  return true
})

onMounted(async () => {
  console.log('DashboardView mounted')
  await initData()
})
</script>

<style scoped>
.dashboard-container {
  padding: 20px;
  height: 100%;
  background-color: var(--el-bg-color-page);
}

.dashboard-content {
  display: flex;
  gap: 20px;
  height: 100%;
  min-width: 0;
}

.sidebar {
  width: 250px;
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
  min-width: 0;
  overflow: auto;
}

.overview-section {
  background: #fff;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.gradient-banner {
  background: linear-gradient(135deg, #13c2c2 0%, #1890ff 100%);
  padding: 24px 32px;
  border-radius: 8px;
  margin-bottom: 24px;
  color: #fff;
}

.banner-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.avatar-wrapper {
  border: 4px solid rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  overflow: hidden;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.user-title {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.user-title h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 500;
}

.user-tags {
  display: flex;
  gap: 8px;
}

.role-tag {
  background: rgba(255, 255, 255, 0.2) !important;
  border: none !important;
  color: #fff !important;
}

.vip-tag {
  background: rgba(255, 197, 23, 0.2) !important;
  border: none !important;
  color: #ffd666 !important;
}

.user-id {
  font-size: 14px;
  opacity: 0.8;
}

.platform-info {
  text-align: right;
}

.platform-info h1 {
  font-size: 28px;
  margin: 0 0 12px;
}

.platform-info .slogan {
  font-size: 16px;
  opacity: 0.9;
  margin: 0;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-top: 20px;
}

.stat-card {
  transition: transform 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: var(--el-color-primary);
  text-align: center;
  padding: 12px 0;
}

.data-table {
  background: #fff;
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow-x: auto;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 48px;
  color: var(--el-text-color-secondary);
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
  color: var(--el-color-info-light-5);
}

.empty-text {
  font-size: 14px;
}

.date-column {
  display: flex;
  align-items: center;
  gap: 8px;
}

.operation-column {
  display: flex;
  justify-content: center;
  gap: 8px;
  white-space: nowrap;
}

:deep(.warning-row) {
  background-color: var(--el-color-warning-light-9);
}

:deep(.success-row) {
  background-color: var(--el-color-success-light-9);
}

:deep(.el-table) {
  --el-table-border-color: var(--el-border-color-lighter);
  --el-table-header-bg-color: var(--el-fill-color-light);
  --el-table-row-hover-bg-color: var(--el-fill-color);
  border-radius: 8px;
  overflow: hidden;
}

:deep(.el-table__header) {
  font-weight: 600;
}

:deep(.el-table__row) {
  transition: background-color 0.3s;
}

:deep(.el-button--small) {
  padding: 5px 12px;
  font-size: 12px;
}

:deep(.el-tag) {
  border-radius: 4px;
  padding: 0 8px;
  height: 24px;
  line-height: 24px;
}

:deep(.el-card) {
  border: none;
  transition:
    transform 0.3s ease,
    box-shadow 0.3s ease;
}

:deep(.el-card:hover) {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
}

:deep(.el-card__header) {
  padding: 16px;
  border-bottom: 1px solid var(--el-border-color-lighter);
}

.dashboard-menu {
  border-right: none;
  margin-top: 20px;
}

:deep(.el-menu-item) {
  border-radius: 4px;
  margin: 4px 0;
  height: 45px;
  line-height: 45px;
}

:deep(.el-menu-item.is-active) {
  background-color: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
}

:deep(.el-menu-item:hover) {
  background-color: var(--el-color-primary-light-8);
}

.title-column {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--el-text-color-primary);
}

.title-column .el-icon {
  font-size: 16px;
  color: var(--el-color-primary);
}

:deep(.el-tag) {
  max-width: 100%;
  white-space: normal;
  height: auto;
  padding: 4px 8px;
  line-height: 1.4;
}

.description-column {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.description-text {
  color: #666;
  line-height: 1.5;
}

.event-date {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #909399;
  font-size: 13px;
}

.event-date .el-icon {
  font-size: 14px;
}

.operation-column .el-button-group {
  display: flex;
  gap: 4px;
}

.schedule-info {
  margin-top: 4px;
  color: var(--el-text-color-secondary);
  font-size: 13px;
}

:deep(.el-button-group) {
  display: inline-flex;
  gap: 4px;
}

:deep(.el-button--primary) {
  --el-button-bg-color: var(--el-color-primary);
  --el-button-border-color: var(--el-color-primary);
  --el-button-hover-bg-color: var(--el-color-primary-light-3);
  --el-button-hover-border-color: var(--el-color-primary-light-3);
}

:deep(.el-button--success) {
  --el-button-bg-color: var(--el-color-success);
  --el-button-border-color: var(--el-color-success);
  --el-button-hover-bg-color: var(--el-color-success-light-3);
  --el-button-hover-border-color: var(--el-color-success-light-3);
}

:deep(.el-button--danger) {
  --el-button-bg-color: var(--el-color-danger);
  --el-button-border-color: var(--el-color-danger);
  --el-button-hover-bg-color: var(--el-color-danger-light-3);
  --el-button-hover-border-color: var(--el-color-danger-light-3);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-table) {
  --el-table-border: none;
  --el-table-border-color: transparent;
  --el-table-cell-border-color: transparent;
}

:deep(.el-table__inner-wrapper::before) {
  display: none;
}

:deep(.el-table__row) {
  background: transparent;
}

:deep(.success-row) {
  background-color: rgba(var(--el-color-success-rgb), 0.1);
}

:deep(.success-row td) {
  background: transparent !important;
}

:deep(.el-table__row:hover td) {
  background-color: var(--el-table-row-hover-bg-color) !important;
}

.header {
  display: none;
}

.admin-tag {
  background: linear-gradient(135deg, #ff4d4f 0%, #ff7875 100%) !important;
  border: none !important;
  color: #fff !important;
}

:deep(.el-table) {
  width: 100% !important;
  overflow-x: auto;
}

:deep(.el-table__body-wrapper) {
  overflow-x: auto;
}

:deep(.el-table__inner-wrapper) {
  min-width: 100%;
}

.operation-column {
  display: flex;
  justify-content: center;
  gap: 8px;
  white-space: nowrap;
}

:deep(.el-table) {
  width: 100% !important;
}

:deep(.el-table__body) {
  width: 100% !important;
}

:deep(.el-table__inner-wrapper) {
  width: 100% !important;
}

:deep(.el-table__body-wrapper) {
  width: 100% !important;
}

:deep(.el-button-group) {
  display: inline-flex;
  gap: 4px;
}

:deep(.el-button--small) {
  padding: 5px 12px;
  font-size: 12px;
}

:deep(.el-table) {
  width: 100% !important;
}

:deep(.el-table__header),
:deep(.el-table__body) {
  width: 100% !important;
  table-layout: fixed !important;
}

:deep(.el-table__cell) {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 添加预约详情模态框样式 */
.consultation-detail {
  padding: 20px;
}

.detail-section {
  margin-bottom: 24px;
  background: #f8f9fa;
  border-radius: 8px;
  padding: 16px;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
  padding-bottom: 8px;
  border-bottom: 1px solid #e4e7ed;
}

.detail-item {
  margin-bottom: 16px;
  display: flex;
  align-items: flex-start;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.detail-item .label {
  width: 100px;
  color: #606266;
  font-weight: 500;
  line-height: 24px;
}

.detail-item .value {
  flex: 1;
  color: #303133;
  line-height: 24px;
}

.service-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.service-tag {
  margin-right: 8px;
}

.no-data {
  color: #909399;
  font-size: 13px;
}

.price {
  font-size: 16px;
  font-weight: 500;
  color: #f56c6c;
}
</style>
